#include "qrcode.h"
#include "wefuckapi.h"

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>

const static QString create_user_statement = "CREATE TABLE IF NOT EXISTS user_record ('user_id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 'ticket' TEXT,'uuid' TEXT,'scan' TEXT,'lang' TEXT,'skey' TEXT,'wxuin' TEXT,'pass_ticket' TEXT,'isgrayscale' TEXT)";
const static QString create_frend_statement = "CREATE TABLE IF NOT EXISTS frend_record ('frend_id' INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, 'user_name' TEXT UNIQUE,'nick_name' TEXT,'head_img_url' TEXT,'sex' TEXT,'remark_name' TEXT,'signature' TEXT,'city' TEXT)";



int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    {
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "sqlite_for_wefuck");
        db.setDatabaseName("wefuckk.db");
        bool ok = db.open();

        QSqlQuery query(db);

        bool success;
        success = query.exec(create_frend_statement);
        if (!success) {

            qDebug() << "create table fail(0)";
            QSqlError lastError = query.lastError();
            qDebug() << lastError.driverText();
            return -1;
        }
        success = query.exec(create_user_statement);
        if (!success) {
            qDebug() << "create table fail(1)";
            return -1;
        }
        db.close();
    }

    QSqlDatabase::removeDatabase("sqlite_for_wefuck");

    qDebug() << "init db successfully";

    qmlRegisterType<QrCode>("com.stupidzhe.QrCode", 1, 0, "QrCode");
    qmlRegisterType<WeFuckApi>("com.stupidzhe.WeFuckApi", 1, 0, "WeFuckApi");


    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}
